# -*- coding: utf-8 -*-

import os
import re
import time
from collections import Counter
import datetime
import csv

# 输入日志文件目录和输出文件路径
current_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
log_directory = os.path.join(current_path, "alllogs\\alllogs\Logs")
csv_file = "error_zs.csv"  # 错误码映射表

dt_obj = datetime.datetime.now()
output_log = "errorret_" + dt_obj.strftime('%Y%m%d%H%M') + '.txt'


def extract_error_with_full_display(directory, output_file):
    error_count = Counter()
    all_error_codes = [ ]

    def process_file(file_path):
        context_buffer = [ ]
        write_context = False

        with open(file_path, 'r', encoding='utf-8') as infile:
            for line in infile:
                timestamp_match = re.match(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})', line)
                if timestamp_match:
                    timestamp = timestamp_match.group(1)
                    context_buffer = [ line.strip() ]

                receive_msg_match = re.search(r'\breceive\s+(\w+)', line)
                if receive_msg_match:
                    context_buffer.append(line.strip())
                    write_context = True

                data_stream_match = re.search(r'packet stream:\s+(\S+)', line)
                if data_stream_match and write_context:
                    context_buffer.append(line.strip())
                # 灵妖错误码标志 ret
                ret_match = re.search(r'ret:\s*(\d+)', line)
                if ret_match and write_context:
                    error_code = ret_match.group(1)
                    error_count [ error_code ] += 1
                    all_error_codes.append(error_code)
                    context_buffer.append(line.strip())
                    with open(output_file, 'a', encoding='utf-8') as outfile:
                        outfile.write("\n".join(context_buffer) + "\n\n")
                    context_buffer = [ ]
                    write_context = False

    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.txt'):
                file_path = os.path.join(root, file)
                process_file(file_path)

    return error_count


def read_csv_and_map_errors(csv_file, error_codes):
    error_mapping = {}
    try:
        with open(csv_file, mode='r', encoding='gbk') as csvfile:
            reader = csv.reader(csvfile)
            next(reader)  # Skip header row if present
            for row in reader:
                if len(row) > 1 and row [ 0 ] in error_codes:
                    error_mapping [ row [ 0 ] ] = row [ 1 ]
    except FileNotFoundError:
        print("CSV文件未找到，请检查文件名和路径是否正确。")
    except Exception as e:
        print(f"读取CSV文件时发生错误: {e}")

    return error_mapping


# 清空输出文件
with open(output_log, 'w', encoding='utf-8') as outfile:
    outfile.write('')

# 提取错误码并统计次数
error_counts = extract_error_with_full_display(log_directory, output_log)
#
# # 打印错误码及其统计次数
# print("\n错误码统计：")
# for code, count in error_counts.items():
#     print(f"{code}: {count}次")

# 读取CSV文件并映射错误码
error_mapping = read_csv_and_map_errors(csv_file, error_counts.keys())

# 打印结果
print("\n错误码：")
for code, value in error_mapping.items():
    print(f"{code}: {value}")
